package com.example.feifei.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.feifei.net.download.bean.FileInfo;
import com.example.feifei.net.download.service.DownloadService;
import com.example.feifei.net.download.service.DownloadService2;
import com.example.feifei.newproject.CustomViewActivity;
import com.example.feifei.newproject.R;
import com.example.feifei.utils.ToastUtil;
import com.example.feifei.view.NumberProgressView;
import com.example.feifei.view.popwindow.ProgressNumber;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 线程下载
 * Created by cff on 2018\6\13 0013.
 */

public class DownLoadFragment extends Fragment implements View.OnClickListener{

    private View root_view;

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.pro_text)
    TextView pro_text;
    @BindView(R.id.start)
    Button start;
    @BindView(R.id.pause)
    Button pause;
    @BindView(R.id.my_progress)
    ProgressBar my_progress;
    @BindView(R.id.progress_percentage)
    NumberProgressView progress_percentage;
    @BindView(R.id.btn_progressStart)
    Button btn_progressStart;
    @BindView(R.id.progress_myView)
    ProgressNumber progress_myView;

    private int progressInt = 0;
    protected static final int WHAT_INCREASE = 1;

    /**************************************************  多线程下载   *********************************************************************/

    @BindView(R.id.manyThreadName)
    TextView manyThreadName;
    @BindView(R.id.many_progressBar)
    ProgressBar many_progressBar;
    @BindView(R.id.many_pro_text)
    TextView many_pro_text;
    @BindView(R.id.many_start)
    Button many_start;
    @BindView(R.id.many_pause)
    Button many_pause;
    //6.0以上读取权限
    private static int WRITE_REQUEST_CODE = 0;
    //单线程下载文件信息
    private FileInfo fileInfo;
    private String url = "http://dldir1.qq.com/weixin/android/weixin6316android780.apk";//单线程下载文件地址
    //多线程下载文件信息
    private FileInfo manyFileInfo;
    private String manyUrl = "http://111.202.99.12/sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk";//多线程下载文件地址

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        root_view = inflater.inflate(R.layout.fragment_download,null);
        ButterKnife.bind(this,root_view);
        initView();
        initDate();
        return root_view;
    }

    private void initDate() {
        my_progress.setProgress(52);
    }

    @Override
    public void onResume() {
        super.onResume();

        start.setOnClickListener(this);
        pause.setOnClickListener(this);
        many_start.setOnClickListener(this);
        many_pause.setOnClickListener(this);
        btn_progressStart.setOnClickListener(this);

        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadService.ACTION_UPDATE);
        getActivity().registerReceiver(mReceiver,filter);

        IntentFilter manyFilter = new IntentFilter();
        manyFilter.addAction(DownloadService2.ACTION_UPDATE);
        manyFilter.addAction(DownloadService2.ACTION_FINISHED);
        getActivity().registerReceiver(manyReceiver,manyFilter);

    }

    private void initView() {
        progressBar.setMax(100);
        fileInfo = new FileInfo(0, url, getUrlFileName(url), 0, 0);
        name.setText("单线程下载文件——"+fileInfo.getFileName());

        many_progressBar.setMax(100);
        manyFileInfo = new FileInfo(1,manyUrl,getUrlFileName(manyUrl),0,0);
        manyThreadName.setText("多线程下载文件"+manyFileInfo.getFileName());
    }

    /**
     * 更新UI的广播接收器
     */
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) {
                int finished = intent.getIntExtra("finished", 0);
                progressBar.setProgress(finished);
                pro_text.setText(new StringBuffer().append(finished).append("%"));
                if(100 == finished){
                    ToastUtil.showMessage(context,"下载完成");
                }
            }
        }
    };

    /**
     * 更新多线程广播接收器
     */
    private BroadcastReceiver manyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadService2.ACTION_UPDATE.equals(intent.getAction())) {
                long finished = intent.getLongExtra("finished", 0);
                int id = intent.getIntExtra("id", 0);
                many_progressBar.setProgress((int) finished);
                many_pro_text.setText(new StringBuffer().append(finished).append("%"));
                //progressBar.setProgress(finished);
            } else if (DownloadService2.ACTION_FINISHED.equals(intent.getAction())) {
                FileInfo fileinfo = (FileInfo) intent.getSerializableExtra("fileinfo");
                //更新进度为100
                many_pro_text.setText("更新完成");
             ToastUtil.showMessage(getActivity(),"多线程下载完成");
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == WRITE_REQUEST_CODE){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Intent intent = new Intent(getActivity(),DownloadService.class);
                intent.setAction(DownloadService.ACTION_START);
                intent.putExtra("fileinfo", fileInfo);
                getActivity().startService(intent);
            }else {
                ToastUtil.showMessage(getContext(),"请打开文件读写权限");
            }
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(getActivity(),DownloadService.class);
        Intent intent_many = new Intent(getActivity(),DownloadService2.class);
        switch (view.getId()){
            case R.id.start:
                if (ContextCompat.checkSelfPermission((CustomViewActivity)getActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {   //权限还没有授予，需要在这里写申请权限的代码
                    // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                    // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                    ActivityCompat.requestPermissions((CustomViewActivity)getActivity(),
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            WRITE_REQUEST_CODE);

                }else { //权限已经被授予，在这里直接写要执行的相应方法即可
                    intent.setAction(DownloadService.ACTION_START);
                    intent.putExtra("fileinfo", fileInfo);
                    getActivity().startService(intent);
                }

                break;
            case R.id.pause:
                intent.setAction(DownloadService.ACTION_PAUSE);
                intent.putExtra("fileinfo", fileInfo);
                getActivity().startService(intent);
                break;
                //多线程下载开始
            case R.id.many_start:
                intent_many.setAction(DownloadService2.ACTION_START);
                intent_many.putExtra("fileinfo", manyFileInfo);
                getActivity().startService(intent_many);
                break;
                //多线程结束
            case R.id.many_pause:
                intent_many.setAction(DownloadService2.ACTION_PAUSE);
                intent_many.putExtra("fileinfo",manyFileInfo);
                getActivity().startService(intent_many);
                break;
                //进度条开始
            case R.id.btn_progressStart:
                progressInt = 0;
                progress_percentage.setProgress(0);
                progress_myView.setProgressInt(0);
                handler.removeMessages(WHAT_INCREASE);
                handler.sendEmptyMessage(WHAT_INCREASE);

                break;
        }
    }
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            progressInt++;
            progress_percentage.setProgress(progressInt);
            progress_myView.setProgressInt(progressInt);
            my_progress.setProgress(progressInt);
            handler.sendEmptyMessageDelayed(WHAT_INCREASE, getRadomNumber(50, 200));
            if (progressInt >= 100) {
                handler.removeMessages(WHAT_INCREASE);
            }
        }
    };
    /**
     * 得到两个整数之间的一个随机数
     *
     * @param start 较小的数
     * @param end   较大的数
     * @return
     */
    public int getRadomNumber(int start, int end) {
        return (int) (start + Math.random() * (end - start));
    }

    /**
     * 获取路径下的文件名
     */
    private String getUrlFileName(String urlPath){
        String fileName = null;
        try {
            if (urlPath.contains("?")){
                fileName = URLDecoder.decode(urlPath.substring(urlPath.lastIndexOf("/")+1, urlPath.indexOf("?")), "UTF-8");
            }else {
                fileName = URLDecoder.decode(urlPath.substring(urlPath.lastIndexOf("/")+1), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(manyReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            getActivity().unregisterReceiver(mReceiver);
        }
    }



}
